<script lang="ts" setup>
import { onBeforeMount, onMounted, ref, nextTick } from 'vue';
import ComCard from './Card.vue';
import { echarts } from '../../utils';

const chartRef = ref<echarts.ECharts>()
const chartDomRef = ref()

const toChartData = (data: any[]) => {
  return {
    data: data.map(_ => ({ ..._, id: _.id + '' })),
    edges: data.reduce((t, a) => {
      return [
        ...t,
        ...(a.containees || []).map(b => {
          return {
            ...b,
            source: a.id + '',
            target: b.target + '',
            isContained: true
          }
        }),
        ...(a.relatees || []).map(b => {
          return {
            ...b,
            source: a.id + '',
            target: b.target + '',
            isRelated: true,
            lineStyle: {
              color: 'green'
            }
          }
        })
      ]
    }, [])
  }
}

const renderChart = (data?: any) => {
  if (!chartRef.value) {
    chartRef.value = echarts.init(chartDomRef.value)
  }
  chartRef.value.setOption({
    series: [
      {
        type: 'graph',
        layout: 'force',
        symbolSize: 15,
        roam: true,
        draggable: true,
        selectedMode: 'single',
        label: {
          show: true
        },
        edgeSymbol: ['none', 'arrow'],
        edgeLabel: {
          fontSize: 12
        },
        lineStyle: {
          opacity: 0.9,
          width: 1,
          curveness: 0.2
        },
        select: {
          itemStyle: {
            color: '#00cdb1',
            borderWidth: 1,
            shadowBlur: 8,
            shadowColor: '#00cdb1'
          }
        },
        force: {
          edgeLength: 30
        },
        ...toChartData([])
      }
    ]
  })
}

const onResize = () => {
  if (chartRef.value) {
    chartRef.value.resize()
  }
}

const onUnmount = () => {
  if (chartRef.value) {
    chartRef.value.dispose()
    chartRef.value = null
  }
}

onMounted(async () => {
  await nextTick()
  renderChart()
  window.addEventListener('resize', onResize)
})

onBeforeMount(onUnmount)
</script>

<template>
  <ComCard title="系统星形拓扑图">
    <div ref="chartDomRef"></div>
  </ComCard>
</template>
